package com.woniu.handler;

import com.woniu.util.JWTUtil;
import com.woniu.util.ResponseResult;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        User user = (User) authentication.getPrincipal();
        String username = user.getUsername();
        String jwt = JWTUtil.creatJWT(username);
        redisTemplate.opsForValue().set("jwt:"+username,jwt,30, TimeUnit.MINUTES);

        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter pw=httpServletResponse.getWriter();
        String sucess = JSON.toJSONString(new ResponseResult<>().ok(jwt));

        pw.print(sucess);
        pw.flush();
        pw.close();
    }
}